/*******************************************************************************
 * Copyright (c) 2010 LegSem.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     LegSem - initial API and implementation
 ******************************************************************************/
package com.legsem.legstar.cci;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.legstar.host.access.HostAccessStrategy;
import com.legstar.host.access.HostAccessStrategyException;
import com.legstar.messaging.ConnectionException;
import com.legstar.messaging.LegStarConnection;
import com.legstar.messaging.LegStarRequest;
import com.legstar.messaging.RequestException;

/**
 * This strategy is useful when the connection is externally managed.
 */
public class LegStarManagedAccessStrategy implements HostAccessStrategy {

    /** Logger. */
    private final Log _log = LogFactory.getLog(getClass());

    /** The host connection. */
    private LegStarConnection connection;

    /**
     * Construct a host strategy for a managed connection.
     * 
     * @param connection the host connection
     */
    public LegStarManagedAccessStrategy(final LegStarConnection connection) {
        this.connection = connection;
    }

    /**
     * (non-Javadoc).
     * 
     * @see com.legstar.host.access.HostAccessStrategy#invoke(com.legstar.messaging.Request)
     *      {@inheritDoc}
     */
    public void invoke(final LegStarRequest request)
            throws HostAccessStrategyException {

        long startTime = System.currentTimeMillis();
        if (_log.isDebugEnabled()) {
            _log.debug("Managed invoke for Request:" + request.getID());
        }
        try {
            connection.connectReuse(request.getAddress().getHostPassword());
            connection.sendRequest(request);
            connection.recvResponse(request);
        } catch (ConnectionException e) {
            request.setException(new RequestException(e));
            throw new HostAccessStrategyException(e);
        } catch (RequestException e) {
            request.setException(new RequestException(e));
            throw new HostAccessStrategyException(e);
        }
        if (_log.isDebugEnabled()) {
            long endTime = System.currentTimeMillis();
            _log.debug("Managed invoke for Request:" + request.getID()
                    + " ended. elapse: " + Long.toString(endTime - startTime)
                    + " ms");
        }
    }

    /**
     * @return the host connection
     */
    public LegStarConnection getHostConnection() {
        return connection;
    }

}
